package com.gitee.mazhenggg.demo.auth.controller;

import com.gitee.mazhenggg.demo.auth.security.SecurityUserDetails;
import com.gitee.mazhenggg.demo.auth.service.JwtService;
import com.gitee.mazhenggg.demo.common.constant.TokenConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private JwtService jwtUtil;

    @GetMapping("/test")
    public ResponseEntity require(HttpSession session) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();

        return ResponseEntity.ok("success");
    }

    @GetMapping("/test3")
    public ResponseEntity require2(HttpSession session,HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.debug("authentication.getName():"+authentication.getName());
        SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
        String jwt = request.getHeader(TokenConstants.ACCESS_TOKEN);
        Map<String, Object> userInfo =jwtUtil.getUserInfoMap(jwt);
        log.debug("jwt:"+jwt);
        log.debug("userName:"+userInfo.get("userName"));
        log.debug("userId:"+userInfo.get("userId"));


        return ResponseEntity.ok("ok");
    }

    @GetMapping("/test2")
    public String require() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();

        return "success";
    }

}